﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using COMOSOFT.Class;
using Merchandising_Software.TrimNew.report;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;

namespace COMOSOFT.MatarialManagement.Forms
{
    public partial class FrmBookMA : Form
    {
        ClassShare cls = new ClassShare("FrmBookMA");
        int BMID;
        int BDID;
        int MAID;
        int MADID;

        string MANo;
        string MALDIDs;
        string Remark;

        double Price;
        double UnitsPrice;
        double Qty;
        
        public FrmBookMA(int _BMID)
        {
            InitializeComponent();
            this.BMID=_BMID;
        }

        List<ClassShare.NodeItem> ListNode = new List<ClassShare.NodeItem>();

        
        private void FrmBookMA_Load(object sender, EventArgs e)
        {            
            this.orderSizeBreakdownTableAdapter1.Fill(this.dataSetBalancing.OrderSizeBreakdown);
        }

        public void AddNew()
        {
            bookingMasterBindingSource.AddNew();
            txt_IssueDate.EditValue = DateTime.Now.ToShortDateString();
            txt_Requester.EditValue = Convert.ToInt64(ClassShare.Usid);
        }

        public void UpdateData()
        {
            try
            {
                if (BMID < 0)
                {
                    bookingMasterBindingSource.EndEdit();
                    bookingMasterTableAdapter.Update(dataSetBalancing.BookingMaster);
                    dataSetBalancing.BookingMaster.AcceptChanges();
                    group_BookDetais.Enabled = true;
                    BMID = Convert.ToInt32(txt_BID.Text);
                }
                else
                {
                    if (Convert.ToInt32(txt_Requester.EditValue) == ClassShare.Usid)
                    {
                        if (MessageBox.Show("Are you sure delete item selected", "Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            dataSetBalancing.BookingMaster.Rows[0].Delete();
                            bookingMasterTableAdapter.Update(dataSetBalancing.BookingMaster);
                            dataSetBalancing.BookingMaster.AcceptChanges();
                            this.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("You don't permission");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void DeleteBMA()
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to delete?", "Delete item", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    dataSetBalancing.BookingMaster[0].Delete();
                    bookingMasterTableAdapter.Update(dataSetBalancing.BookingMaster);
                    dataSetBalancing.BookingMaster.AcceptChanges();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void loadData()
        {
            try
            {
                employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
                mAListDetailsTableAdapter.Fill(this.dataSetBalancing.MAListDetails);
                sp_BookChooseMATableAdapter.Fill(this.dataSetBalancing.sp_BookChooseMA);
                sp_BookChooseTrimListTableAdapter.Fill(this.dataSetBalancing.sp_BookChooseTrimList);
                supplierTableAdapter.Fill(dataSetMatarial.Supplier);
                if (BMID > 0)
                {
                    this.bookingMasterTableAdapter.Fill(this.dataSetBalancing.BookingMaster, BMID);
                    this.sp_BookDetailsTableAdapter.Fill(this.dataSetBalancing.sp_BookDetails,BMID);
                    group_BookDetais.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataNavigator_BookMA_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "Save")
                {

                    if (BMID < 0)
                    {
                        bookingMasterBindingSource.EndEdit();
                        bookingMasterTableAdapter.Update(dataSetBalancing.BookingMaster);
                        dataSetBalancing.BookingMaster.AcceptChanges();
                        group_BookDetais.Enabled = true;
                        BMID = Convert.ToInt32(txt_BID.Text);
                    }

                    //Update Details
                    if (ListNode.Count > 0)
                    {
                        foreach (ClassShare.NodeItem node in ListNode)
                        {
                            MAID = node.MAID;
                            MADID = node.MADID;
                            Qty = node.Qty;
                            UnitsPrice = node.Unitprice;
                            MALDIDs = node.MALDIDs;

                            DataTable dtb = cls.GetData("sp_BookDetailsInsert", new string[] { "@BMID", "@MAID", "@MADID", "@UnitPrice", "@Qty" }, new object[] { BMID, MAID, MADID, UnitsPrice, Qty });
                            if (MALDIDs != null)
                            {
                                string[] arr = MALDIDs.Split(new string[] { "," }, StringSplitOptions.None);
                                for (int i = 0; i < arr.Count(); i++)
                                {
                                    cls.UpdateData("sp_BookAllocateInsert", new string[] { "@BDID", "@MALDID" }, new object[] { Convert.ToInt32(dtb.Rows[0][0]), Convert.ToInt32(arr[i]) });
                                }
                            }
                        }                        
                    }
                    //---
                    group_BookDetais.Enabled = true;
                    this.Text = txt_BookNo.Text;
                    loadData();

                }
                else
                {
                    if (e.Button.Tag.ToString() == "Preview")
                    {
                        Preview();
                    }
                    else
                    {
                        if (Convert.ToInt32(txt_Requester.EditValue) == ClassShare.Usid)
                        {
                            if (MessageBox.Show("Are you sure delete item selected?", "Deletion...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                dataSetBalancing.BookingMaster.Rows[0].Delete();                               
                                bookingMasterTableAdapter.Update(dataSetBalancing.BookingMaster);
                                dataSetBalancing.BookingMaster.AcceptChanges();
                                this.Close();
                            }
                        }
                        else
                        {
                            MessageBox.Show("You don't permission!");
                        }
                    }
                }               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gridView_BookDetails_DoubleClick(object sender, EventArgs e)
        {
            if (gridView_BookDetails.FocusedRowHandle >= 0)
            {
                sp_BookAllocateTableAdapter.Fill(dataSetBalancing.sp_BookAllocate, Convert.ToInt32(gridView_BookDetails.GetFocusedDataRow()["BDID"]));
                this.supplierTableAdapter.Fill(this.dataSetMatarial.Supplier);                
            }
        }
        //--------------
        private void gridView_BookDetails_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (view.FocusedRowHandle >= 0 && !view.IsGroupRow(e.RowHandle))
                {
                    MANo = view.GetFocusedDataRow()["MANo"].ToString();
                    if (view.GetFocusedDataRow()["BDID"].ToString() != "")
                        BDID = Convert.ToInt32(view.GetFocusedDataRow()["BDID"]);
                    if (view.GetFocusedDataRow()["UnitsPrice"].ToString() != "")
                        UnitsPrice = Convert.ToDouble(view.GetFocusedDataRow()["UnitsPrice"]);
                    else
                        UnitsPrice = 0;
                    if (view.GetFocusedDataRow()["BQty"].ToString() != "")
                        Qty = Convert.ToDouble(view.GetFocusedDataRow()["BQty"]);
                    else
                        Qty = 0;                   
                    Price = Qty*UnitsPrice;
                    Remark = view.GetFocusedDataRow()["Remarks"].ToString();

                    cls.UpdateData("sp_BookUpdate", new string[] { "@BDID", "@MANo", "@Price", "@UnitsPrice", "@BQty", "@Remarks" }, new object[] { BDID, MANo, Price, UnitsPrice, Qty, Remark });
                    loadData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gridControl_BookDetails_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (gridView_BookDetails.FocusedRowHandle >= 0)
                {
                    sp_BookAllocateTableAdapter.Fill(dataSetBalancing.sp_BookAllocate, Convert.ToInt32(gridView_BookDetails.GetFocusedDataRow()["BDID"]));
                    this.supplierTableAdapter.Fill(this.dataSetMatarial.Supplier);                    
                }
            }
        }

        private void bnt_BCancel_Click(object sender, EventArgs e)
        {
            PopupContainerEdit pp = gridView_BookDetails.ActiveEditor as PopupContainerEdit;
            pp.ClosePopup();
        }

        private void bnt_BOK_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_BookMA as GridView;
                GridView cView= view.GetDetailView(view.FocusedRowHandle, 0) as GridView;
                if (view.FocusedRowHandle >= 0 && !view.IsGroupRow(view.FocusedRowHandle))
                {
                    int MAID = Convert.ToInt32(view.GetFocusedDataRow()["MAID"]);
                    int MADID = Convert.ToInt32(view.GetFocusedDataRow()["MADID"]);
                    if (view.GetFocusedDataRow()["BookQty"].ToString() != "")
                        Qty = Convert.ToInt16(view.GetFocusedDataRow()["BookQty"]);
                    DataTable dtb= cls.GetData("sp_BookDetailsInsert", new string[] { "@BMID", "@MAID", "@MADID", "@Qty" }, new object[] { BMID, MAID, MADID, Qty });
                    if (cView != null)
                    {
                        int[] rows = cView.GetSelectedRows();
                        foreach (int i in rows)
                        {
                            cls.UpdateData("sp_BookAllocateInsert", new string[] { "@BDID", "@MALDID" }, new object[] { Convert.ToInt32(dtb.Rows[0][0]), Convert.ToInt32(cView.GetDataRow(i)["MALDID"]) });
                        }
                        cView.ClearSelection();
                    }
                    loadData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gridView_BookDetails_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Art")
            {
                this.sp_BookChooseMATableAdapter.Fill(this.dataSetBalancing.sp_BookChooseMA);
                this.sp_BookChooseTrimListTableAdapter.Fill(this.dataSetBalancing.sp_BookChooseTrimList);
            }
        }

        public void ShowControl()
        {
            dataNavigator_BookMA.Visible = true; 
        }

        private void gridView_BookMA_MasterRowExpanded(object sender, CustomMasterRowEventArgs e)
        {
            GridView view = sender as GridView;
            GridView cView= view.GetDetailView(view.FocusedRowHandle, 0) as GridView;
            cView.ClearSelection();
            orderSizeBreakdownTableAdapter1.Fill(dataSetBalancing.OrderSizeBreakdown);
        }
        public void SetValue(List<ClassShare.NodeItem> ListItem)
        {
            ListNode.Clear();
            foreach (ClassShare.NodeItem item in ListItem)
            {
                ListNode.Add(item);
            }
        }

        #region[ContextMenu]
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_BookDetails as GridView;
                if (MessageBox.Show("Are you sure delete?", "Comfirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    int[] arrItem = view.GetSelectedRows();
                    foreach (int index in arrItem)
                    {
                        int BDID = Convert.ToInt32(view.GetDataRow(index)["BDID"]);
                        cls.UpdateData("sp_BookMADetailsDelte", new string[] { "@BDID" }, new object[] { BDID });
                    }
                    loadData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }      

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            loadData();
        }

        private void saveLayoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cls.SaveLayout(gridView_BookDetails,ClassShare.lcMaterial+"LayOut_BookMADetails.XML");
        }
        #endregion

        public void Preview()
        {
            rptTrimBooking rptBook = new rptTrimBooking(BMID);
            ReportPrintTool printTool = new ReportPrintTool(rptBook);
            printTool.ShowRibbonPreview(UserLookAndFeel.Default);
        }
    }
}
